import { useEffect } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { DictData } from '../page/system/dict/types';
import { createStorePaginateListKey, paginateRequest } from '../redux/paginateReducer';
import { AppStore } from '../types';

const model = 'system';
const table = 'dict/data';

const baseParams = {
  model,
  table,
  pageNum: 1,
  pageSize: 1000,
};
type HookDictData = { [x: string]: DictData[] };
export default function useDict(...args: string[]) {
  const dispatch = useDispatch();

  const dicts: HookDictData = useSelector((state: AppStore) => {
    let _dicts: HookDictData = {};
    for (let type of args) {
      let _statusList = state.paginate?.[createStorePaginateListKey({ ...baseParams, params: { dictType: type } })];
      _dicts[type] = _statusList?.results ?? [];
    }
    return _dicts;
  }, shallowEqual);

  useEffect(() => {
    if (!args.length) return;
    for (let type of args) {
      dispatch(paginateRequest({ ...baseParams, params: { dictType: type } }));
    }
  }, []); //eslint-disable-line

  return dicts;
}

export function dictDataOptions(list?: DictData[]) {
  let options: { label: string; value: string }[] = [];
  let _list = list ?? [];
  if ((_list.length || 0) > 0) {
    _list.forEach((i) => {
      options.push({ label: i.dictLabel!, value: i.dictValue! });
    });
  }
  return options;
}
